package com.endoc.agingtools.view;

import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.endoc.agingtools.FinalStaticString;
import com.endoc.agingtools.ItemBean;
import com.endoc.agingtools.MainActivity;
import com.endoc.agingtools.R;
import com.endoc.agingtools.adapter.DeviceRecycleViewAdapter;
import com.endoc.agingtools.adapter.KaweiRecycleViewAdapter;
import com.endoc.agingtools.litepal.BindDevice;
import com.endoc.agingtools.utils.BleUtils;
import com.endoc.agingtools.utils.ToastUtils;

import org.litepal.LitePal;

import java.util.List;

import cn.com.heaton.blelibrary.ble.Ble;
import cn.com.heaton.blelibrary.ble.model.BleDevice;

public class PopupWindows {

    private static CheckBox mCheckBox;

    public static PopupWindow getPopWnd(final Context context, View rootView, final ItemBean itemBean, List<BleDevice> searchDevice, final RecyclerView.Adapter kaiweiAdapter) {
        TextView tvShowDeviceName;
        TextView spListJia;
        TextView spListId;
        EditText etMin;
        EditText etMax;
        final RecyclerView rcDeviceList;
        Button btCreateBd;
        final View contentView = LayoutInflater.from(context).inflate(R.layout.device_detail_popuplayout, null);
        final PopupWindow popWnd = new PopupWindow(context);
        popWnd.setContentView(contentView);
        popWnd.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popWnd.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        popWnd.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
        contentView.findViewById(R.id.bt_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWnd.dismiss();
            }
        });
        spListJia = contentView.findViewById(R.id.sp_list_jia);
        spListId =   contentView.findViewById(R.id.sp_list_id);
        etMin = (EditText)  contentView.findViewById(R.id.et_min);
        etMax = (EditText)  contentView.findViewById(R.id.et_max);

        rcDeviceList = (RecyclerView) contentView.findViewById(R.id.rc_device_list);
        tvShowDeviceName = (TextView)  contentView.findViewById(R.id.tv_show_device_name);
        //当前
        mCheckBox = ((CheckBox)contentView.findViewById(R.id.cb_select_device));
        //连接状态
        final TextView connectStatus = (TextView)contentView.findViewById(R.id.tv_connect_statu);
        if(itemBean.getBleDevice()!=null){
            tvShowDeviceName.setText(itemBean.getBleDevice().getBleName());//设置设备名称
        }

        //查看已连接设备中是否有此设备
        List<BleDevice> connectedDevices = Ble.getInstance().getConnectedDevices();
        for (BleDevice ble: connectedDevices) {
            //如果当前设备已连接,那么设置已连接
            if(ble.getBleName().equals(itemBean.getDeviceName())){
                connectStatus.setText("连接");
                connectStatus.setTextColor( Color.parseColor("#FF5F51"));
                break;
            }else {
                connectStatus.setText("断开");
                connectStatus.setTextColor(Color.parseColor("#323232"));
            }
        }



        final LinearLayoutManager manager = new LinearLayoutManager(context);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        rcDeviceList.setLayoutManager(manager);
        /*mDeviceRecycleViewAdapter= new DeviceRecycleViewAdapter(this,value,mBindDevice,rcDevice);
        rcDevice.setAdapter(mDeviceRecycleViewAdapter);*/


        final DeviceRecycleViewAdapter    deviceRecycleViewAdapter = new DeviceRecycleViewAdapter(context,itemBean,searchDevice,rcDeviceList,mCheckBox,kaiweiAdapter,connectStatus);

         if(context instanceof MainActivity){
             ((MainActivity) context).register(deviceRecycleViewAdapter);
         }
        rcDeviceList.setAdapter(deviceRecycleViewAdapter);

        spListId.setText("卡位"+itemBean.getKaiwei());

        final RecyclerView.Adapter finalDeviceRecycleViewAdapter = deviceRecycleViewAdapter;


        contentView.findViewById(R.id.bt_start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //如果没有连接,那么直接连接操作
                if(!itemBean.getBleDevice().isConnected()){
                    //这里设置直接更新条目为0的,是bug
                    BleUtils.connectDevice(itemBean.getBleDevice(),kaiweiAdapter,finalDeviceRecycleViewAdapter,null);
                }else {
                    ToastUtils.showToast(context,"设备已连接");
                }
            }
        });

        contentView.findViewById(R.id.bt_end).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(itemBean.getBleDevice().isConnected()){
                    BleUtils.disConnecrDevice(itemBean.getBleDevice());
                }
            }
        });
        btCreateBd = (Button)  contentView.findViewById(R.id.bt_create_bd);

        contentView.findViewById(R.id.bt_research).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    if(context instanceof  MainActivity){
                        ((MainActivity)context).startSearch();
                    }
            }
        });

        //默认CheckBox不可见
        mCheckBox.setVisibility(View.GONE);
        connectStatus.setVisibility(View.GONE);
        mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                BindDevice bindDevice = LitePal.where("isUser = ? and kawei = ?", "1", itemBean.getKaiwei() + "").findFirst(BindDevice.class);
                if(isChecked){
                    mCheckBox.setText(bindDevice.getDeviceName());
                    rcDeviceList.setVisibility(View.INVISIBLE);
                    mCheckBox.setVisibility(View.VISIBLE);
                    connectStatus.setVisibility(View.VISIBLE);
                }else {
                    mCheckBox.setVisibility(View.GONE);
                    rcDeviceList.setVisibility(View.VISIBLE);
                    connectStatus.setVisibility(View.GONE);

                    //将原先绑定设备从数据库中移除
                    if(bindDevice!=null) {
                        BindDevice unbindDevice = new BindDevice();
                        unbindDevice.setUser(false);
                        unbindDevice.setKawei(itemBean.getKaiwei());
                        unbindDevice.saveOrUpdate("deviceName = ?", bindDevice.getDeviceName());  //更改绑定设备为未绑定
                        //如果当前连接的设备列表中有此设备,那么就进行断开操作
                        List<BleDevice> connectedDevices = Ble.getInstance().getConnectedDevices();
                        for (int i = 0; i < connectedDevices.size(); i++) {
                            if (connectedDevices.get(i).getBleName().equals(bindDevice.getDeviceName())) {
                                Ble.getInstance().disconnect(connectedDevices.get(i));
                                break;
                            }
                        }
                        itemBean.setDeviceName(null);//修改不生效
                        //更新主界面的ui
                        kaiweiAdapter.notifyDataSetChanged();
                    }

                }


            }
        });

        //如果当前的CheckBox绑定了东西,那么就显示,否则就显示搜索列表
        BindDevice bindDevice = LitePal.where("isUser = ? and kawei = ?", "1", itemBean.getKaiwei() + "").findFirst(BindDevice.class);
        //当前卡位已经有绑定的设备话,就直接显示绑定的设备
        if(bindDevice!=null){
            mCheckBox.setChecked(true);
        }else {
            //否则显示列表
            mCheckBox.setChecked(false);
        }
        return popWnd;
    }
}
